import { Extension } from '@tiptap/core'
import { Plugin, PluginKey } from 'prosemirror-state'
import { EditorView } from 'prosemirror-view'
import { nanoid } from "nanoid";
// 工具函数
import {
    max_text_length
  } from "@/common/utils/richTextProcessing.js";

  // 对于有选区的情况下, 不做处理的按键
const notEvent = [
    'Shift',
    'Control',
    'Alt',
    'ArrowLeft',
    'ArrowRight',
    'ArrowUp',
    'ArrowDown',
    'End',
    'Home',
    'PageUp',
    'PageDown',
    'Escape',
]
export const backspacePlugin = (getEdit) => Extension.create({
    name: 'handleBackspace',
    addProseMirrorPlugins() {
        return [
            new Plugin({
                key: new PluginKey('handleBackspace'),
                props: {
                    handleKeyDown(view, event) {
                        // 检测是否按下了Backspace或Delete键
                        const editor = getEdit();
                        const { state, dispatch } = view;
                        const { selection, tr } = state;
                        const { from, to, $from, $to } = selection;
                        const size = state.doc.content.size
                        const entireDocSelected = to <= size;
                        const nodeType = state.doc.type.schema.nodes.speak.name
                        let vText =''

                          // 检测是否全选了文档内容
                          if (entireDocSelected && (from <= 1) && !selection.empty) {
                            // 排除功能按钮
                            if (event.key != 'Backspace' && event.key != 'Delete' && !notEvent.includes(event.key) && !event.ctrlKey) {
                                event.preventDefault();
                                const id = nanoid();
                                editor.commands.deleteRange({ from, to })
                                editor.commands.deleteSelection()
                                editor.commands.setContent(`<speak subId="${id}"><p></p></speak>`)
                                return true;
                            }
                        }
                        // console.log(event.key,'删除按钮=====================');
                        if (event.key === 'Control ' || event.key === 'v') {
                            const text = state.doc.textBetween(selection.from, selection.to, '')
                            console.log(text,'文本粘贴');
                            if(vText){
                                editor.commands.setContent(`<speak subId="${id}"><p>${vText}</p></speak>`)
                            }
                        }
                        if (event.key === 'Control ' || event.key === 'x') {
                             const text = state.doc.textBetween(selection.from, selection.to, '')
                            // 数量不大于一个了, 并且内部的文字是空的, 不允许删除
                            // 将选中的文本复制到剪贴板
                            navigator.clipboard.writeText(text)
                            .then(() => {
                                    vText = text
                                    console.log('文本已成功复制到剪贴板:', text);
                                    // 删除选中的内容
                                    // editor.commands.deleteRange({ from, to });
                                })
                            .catch((error) => {
                                    console.error('复制文本到剪贴板时出错:', error);
                                });
                            if(selection.from == 0 || selection.from == 1){
                                event.preventDefault();
                                const id = nanoid();
                                editor.commands.deleteRange({ from, to })
                                editor.commands.deleteSelection()
                                editor.commands.setContent(`<speak subId="${id}"><p></p></speak>`)
                                return true
                            }else{
                                editor.commands.deleteRange({ from, to })
                            }
                            //     console.log(text, '选择的文案???????')
                            // event.preventDefault();
                            // const id = nanoid();
                            // editor.commands.deleteRange({ from, to })
                            // editor.commands.deleteSelection()
                            // editor.commands.setContent(`<speak subId="${id}"><p></p></speak>`)
                            return true;
                        }
                        if (event.key === 'Backspace' || event.key === 'Delete') {
                            console.log('点击了删除1');
                            // 用户没有选中任何内容
                            if (selection.empty) {
                                // 
                                // if (nodeType == 'speak') {
                                let dotComponentsCount = 0;
                                state.doc.descendants((node) => {
                                    if (node.type.name == nodeType) {
                                        dotComponentsCount++;
                                    }
                                });
                                if (dotComponentsCount > 1) {
                                    // 数量大于一个 并且没有选区 判断光标的位置是否在第一个
                                    if (from <= 1) return true
                                    return false;
                                } else {
                                    if ($from.parent.textContent === '') {
                                        // 数量不大于一个了, 并且内部的文字是空的, 不允许删除
                                        event.preventDefault();
                                        return true;
                                    }
                                }
                            } else {
                                // 
                                // 检测是否全选了文档内容
                                if (entireDocSelected && (from <= 1)) {
                                    event.preventDefault();
                                    const id = nanoid();
                                    editor.commands.deleteRange({ from, to })
                                    editor.commands.deleteSelection()
                                    editor.commands.setContent(`<speak subId="${id}"><p></p></speak>`)
                                    // 调用自定义的重置文档内容方法
                                    return true;
                                } else {
                                    editor.commands.deleteRange({ from, to })
                                    const json = editor.getHTML()
                                    editor.commands.setContent(json)
                                    editor.commands.focus(from)
                                    return true
                                }
                            }
                            return false;
                        }
                        else if (event.key == 'Enter') {

                            const font_num = editor.storage.characterCount.characters()
                            // if (font_num >= max_text_length) {
                            //     event.preventDefault()
                            //     return true
                            // }
                            if ($from.parent.content.size == 0) {
                                // 
                                event.preventDefault()
                                // 文本为空, 直接插入一个新节点
                                editor.commands.insertContentAt(from + 1, `<speak subId="${nanoid()}"><p></p></speak>`);
                                return true
                            }
                            if ($from.parent.content.size == $from.parentOffset) {
                                // 在文本最后一行, 创建一个新节点
                                editor.commands.insertDotComponent();
                                return true
                            }
                            // 代表当前光标在开头位置
                            if ($from.parentOffset == 0) {
                                event.preventDefault()
                                editor.commands.handleTopEnter()
                                return true
                            }

                            // 在中间位置, 
                            // if ($from.parent.content.size != $from.parentOffset && $from.parentOffset != 0) {
                            //     // event.preventDefault()
                            //     editor.commands.handleCenterEnter()
                            //     // return true
                            // }

                        } else if (event.key == 'ArrowLeft' || event.key == 'ArrowRight') {
                            // 
                        }
                    },
                },
            })
        ]
    }
});
